package com.xjm.api.admin;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.xjm.entity.dto.ConfigDto;
import com.xjm.entity.vo.Result;
import com.xjm.service.ConfigService;
import com.xjm.excption.AppException;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/config")
public class ConfigController {
    private final ConfigService configService;

    @GetMapping("/get/{key}")
    public Result<JSON> get(@PathVariable String key) {
        JSON value = configService.get(key);
        if (value == null){
            throw new AppException("配置不存在");
        }
        return Result.success(JSONUtil.parse(value));
    }

    @PostMapping("/set")
    public Result<Void> set(@RequestBody @Validated ConfigDto dto) {
        if (!configService.set(dto.getKey(), JSONUtil.parse(dto.getValue()))){
            return Result.error("设置失败");
        }
        return Result.success("设置成功");
    }

    @PostMapping("/update")
    public Result<Void> update(@RequestBody @Validated ConfigDto dto) {
        if (!configService.update(dto.getKey(), JSONUtil.parse(dto.getValue()))){
            return Result.error("设置失败");
        }
        return Result.success("设置成功");
    }
}
